<?php
namespace app\mq;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class MessageQueue
{
    public function pushMessage($exchange,$routing_key ,$data)
    {
        $json = json_encode($data);
        $rabbitMqConf =config('base.rabbit_mq');
        $connection = new AMQPStreamConnection( $rabbitMqConf['host'], $rabbitMqConf['port'], $rabbitMqConf['user'], $rabbitMqConf['pwd'], $rabbitMqConf['vhost']);
        $channel = $connection->channel();
        $channel->exchange_declare($exchange, 'topic', false, false, false);
        $messageBody = gzcompress($json);
        $message = new AMQPMessage($messageBody, array('content_type' => 'text/plain', 'delivery_mode' => 2));//AMQPMessage::DELIVERY_MODE_PERSISTENT
//        $message = new AMQPMessage($messageBody);
        $channel->basic_publish($message, $exchange, $routing_key);
        $channel->close();
        $connection->close();
        return true;
    }

    public function pushMessageQueen($mqName,$msg)
    {
        $rabbitMqConf =config('base.rabbit_mq');
        $connection = new AMQPStreamConnection( $rabbitMqConf['host'], $rabbitMqConf['port'], $rabbitMqConf['user'], $rabbitMqConf['pwd'], $rabbitMqConf['vhost']);
        $channel = $connection->channel();
        $queueConfig = $rabbitMqConf['rabbit_mq_queue'][$mqName];
        $exchange=$queueConfig['exchange_name'];
        $queue=$queueConfig['queue_name'];
        $channel->queue_declare($queue, false, true, false, false);
        $channel->exchange_declare($exchange, 'direct', false, true, false);
        $channel->queue_bind($queue, $exchange);
        $messageBody = $msg;
        echo  $messageBody.'<br>'.$exchange;
        $message = new AMQPMessage($messageBody, array('content_type' => 'text/plain', 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT));

        $channel->basic_publish($message, $exchange);
        $channel->close();
        $connection->close();
        return true;
    }
}